package com.evan.review.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.evan.review.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * HandlerThread使用示例
 * 
 * 本Activity演示HandlerThread的使用，主要包括：
 * 1. HandlerThread的创建和使用
 * 2. 在子线程中执行任务
 * 3. 从子线程切换到主线程更新UI
 * 4. 线程间的通信
 * 5. HandlerThread的正确退出方式
 */
public class HandlerThreadActivity extends AppCompatActivity {
    
    // 消息类型
    private static final int MSG_DOWNLOAD_IMAGE = 1;
    private static final int MSG_PROCESS_IMAGE = 2;
    private static final int MSG_UPLOAD_IMAGE = 3;
    
    // UI组件
    private TextView tvStatus;
    private TextView tvThreadInfo;
    private Button btnStartTasks;
    private Button btnStopTasks;
    
    // 后台线程
    private HandlerThread backgroundThread;
    private Handler backgroundHandler;
    
    // 主线程Handler
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    // 任务计数器
    private final AtomicInteger taskCounter = new AtomicInteger(0);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_handler_thread);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        
        initViews();
        setupListeners();
        
        // 创建并启动HandlerThread
        createHandlerThread();
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tv_status);
        tvThreadInfo = findViewById(R.id.tv_thread_info);
        btnStartTasks = findViewById(R.id.btn_start_tasks);
        btnStopTasks = findViewById(R.id.btn_stop_thread);
    }
    
    private void setupListeners() {
        btnStartTasks.setOnClickListener(v -> {
            if (backgroundHandler != null) {
                // 执行三个序列化的任务
                executeSequentialTasks();
                
                tvStatus.setText("已安排任务...");
                btnStartTasks.setEnabled(false);
                
                // 5秒后重新启用按钮
                mainHandler.postDelayed(() -> btnStartTasks.setEnabled(true), 5000);
            } else {
                Toast.makeText(this, "后台线程未启动", Toast.LENGTH_SHORT).show();
            }
        });
        
        btnStopTasks.setOnClickListener(v -> {
            // 安全地退出HandlerThread
            quitHandlerThread();
            tvStatus.setText("后台线程已停止");
            
            // 2秒后重新创建HandlerThread
            mainHandler.postDelayed(() -> {
                createHandlerThread();
                tvStatus.setText("后台线程已重新创建");
            }, 2000);
        });
    }
    
    /**
     * 创建并启动HandlerThread
     */
    private void createHandlerThread() {
        // 创建HandlerThread，并指定线程名称和优先级
        backgroundThread = new HandlerThread("ImageProcessingThread", 
                Process.THREAD_PRIORITY_BACKGROUND);
        
        // 启动线程，初始化Looper
        backgroundThread.start();
        
        // 使用HandlerThread的Looper创建Handler
        backgroundHandler = new Handler(backgroundThread.getLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_DOWNLOAD_IMAGE:
                        downloadImage((String) msg.obj);
                        break;
                        
                    case MSG_PROCESS_IMAGE:
                        processImage((String) msg.obj);
                        break;
                        
                    case MSG_UPLOAD_IMAGE:
                        uploadImage((String) msg.obj);
                        break;
                }
            }
        };
        
        // 更新线程信息
        updateThreadInfo();
    }
    
    /**
     * 安全地退出HandlerThread
     */
    private void quitHandlerThread() {
        if (backgroundThread != null) {
            // 移除所有待处理的消息
            backgroundHandler.removeCallbacksAndMessages(null);
            
            // 安全退出，等待所有消息处理完毕
            backgroundThread.quitSafely();
            
            // 等待线程结束
            try {
                backgroundThread.join();
                backgroundThread = null;
                backgroundHandler = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 执行序列化的任务示例
     */
    private void executeSequentialTasks() {
        final int taskId = taskCounter.incrementAndGet();
        final String imageUrl = "https://example.com/image" + taskId + ".jpg";
        
        // 任务1: 下载图片
        Message downloadMsg = Message.obtain(backgroundHandler, MSG_DOWNLOAD_IMAGE, imageUrl);
        backgroundHandler.sendMessage(downloadMsg);
        
        // 任务2: 处理图片 (将在下载完成后执行)
        Message processMsg = Message.obtain(backgroundHandler, MSG_PROCESS_IMAGE, imageUrl);
        backgroundHandler.sendEmptyMessageDelayed(MSG_PROCESS_IMAGE, 1000);
        
        // 任务3: 上传图片 (将在处理完成后执行)
        Message uploadMsg = Message.obtain(backgroundHandler, MSG_UPLOAD_IMAGE, imageUrl);
        backgroundHandler.sendEmptyMessageDelayed(MSG_UPLOAD_IMAGE, 2000);
    }
    
    /**
     * 模拟下载图片任务
     */
    private void downloadImage(String url) {
        // 显示当前线程信息
        logThreadInfo("下载图片");
        
        // 模拟耗时操作
        SystemClock.sleep(500);
        
        // 在主线程更新UI
        mainHandler.post(() -> tvStatus.setText("下载图片: " + url));
    }
    
    /**
     * 模拟处理图片任务
     */
    private void processImage(String url) {
        // 显示当前线程信息
        logThreadInfo("处理图片");
        
        // 模拟耗时操作
        SystemClock.sleep(700);
        
        // 在主线程更新UI
        mainHandler.post(() -> tvStatus.setText("处理图片: " + url));
    }
    
    /**
     * 模拟上传图片任务
     */
    private void uploadImage(String url) {
        // 显示当前线程信息
        logThreadInfo("上传图片");
        
        // 模拟耗时操作
        SystemClock.sleep(600);
        
        // 在主线程更新UI
        mainHandler.post(() -> tvStatus.setText("上传完成: " + url));
    }
    
    /**
     * 记录线程信息并显示在UI上
     */
    private void logThreadInfo(String action) {
        Thread currentThread = Thread.currentThread();
        String threadName = currentThread.getName();
        long threadId = currentThread.getId();
        
        String timeStamp = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
                .format(new Date());
        
        final String info = String.format("[%s] %s - Thread: %s (ID: %d)", 
                timeStamp, action, threadName, threadId);
        
        // 在主线程更新UI
        mainHandler.post(() -> {
            String currentText = tvThreadInfo.getText().toString();
            tvThreadInfo.setText(info + "\n" + currentText);
        });
    }
    
    /**
     * 更新线程信息UI
     */
    private void updateThreadInfo() {
        if (backgroundThread != null) {
            String threadInfo = "HandlerThread名称: " + backgroundThread.getName() + 
                    "\n线程ID: " + backgroundThread.getId() + 
                    "\n线程优先级: " + backgroundThread.getPriority();
            
            tvThreadInfo.setText(threadInfo);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 清理主线程Handler的回调和消息
        mainHandler.removeCallbacksAndMessages(null);
        
        // 退出HandlerThread
        quitHandlerThread();
    }
} 